<template>
  <div class="container" v-loading="loading">
    <el-divider content-position="left"><span class="title-left-color">用户基本信息</span></el-divider>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="5">
          <el-form-item label="商品分类：" prop="category_ids">
            <el-select v-model="form.category_ids" multiple placeholder="请选择分类">
              <el-option v-for="item in selectCategories" :key="item.id" :label="item.name" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" plain @click="getMallCategoryInfo">刷新</el-button>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品名称：" prop="goods_name">
            <el-input v-model.trim="form.goods_name" maxlength="50" placeholder="商品名称"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品状态：" prop="status">
            <el-select v-model.trim="form.status" placeholder="请选择状态" class="">
              <el-option v-for="item in selectStatus" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="运费模板：" prop="deliver_id">
            <el-select v-model.trim="form.deliver_id" placeholder="请选择运费模板" filterable class="">
              <el-option v-for="item in selectFreighTemplate" :label="item.deliver_name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" plain @click="getMallDeliverInfo">刷新</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="成本价：" prop="cost_price">
            <el-input v-model.trim="form.cost_price" maxlength="11" placeholder="请输入成本价">
              <template v-slot:append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="批发价：" prop="wholesale_price">
            <el-input v-model.trim="form.wholesale_price" placeholder="请输入批发价">
              <template v-slot:append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="零售价：" prop="retail_price">
            <el-input v-model.trim="form.retail_price" placeholder="请输入零售价">
              <template v-slot:append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="淘宝价：" prop="official_price">
            <el-input v-model.trim="form.official_price" placeholder="请输入淘宝价">
              <template v-slot:append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="货号：" prop="goods_no">
            <el-input v-model.trim="form.goods_no" placeholder="请输入货号"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否使用货号：" prop="is_goods_no">
            <el-select v-model.trim="form.is_goods_no" clearable placeholder="请选择" class="">
              <el-option v-for="item in selectWhether" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="排序：" prop="sort">
            <el-input v-model.trim.number="form.sort" placeholder="请输入排序"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="最多可抵扣红包：" prop="red_packet_price">
            <el-input v-model.trim="form.red_packet_price" placeholder="请输入最多可抵扣红包">
              <template v-slot:append>个</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="发布平台：" prop="platform_type">
            <el-select v-model.trim="form.platform_type" clearable multiple placeholder="请选择发布的平台" class="">
              <el-option v-for="item in selectPlatform" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="商品卖点：" prop="selling_poiont">
            <el-input type="textarea" placeholder="请输入商品卖点" v-model.trim="form.selling_poiont" maxlength="60" :rows="3" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="商品主图：" prop="goods_image">
            <UploadImageInfo :imageWidth="178" :imageHeight="178" :limit="200" suggestInfo="建议：尺寸100*100,大小200k以下" v-model:disabledbtn="disabledbtn" v-model:loading="loading" imageKey="goods_image" v-model:form="form" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="轮播视频：" prop="goods_video">
            <UploaVideoInfo suggestInfo="建议：上传20s以内的短视频，大小10M以下" v-model:disabledbtn="disabledbtn" v-model:loading="loading" videoKey="goods_video" v-model:form="form" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="商品轮播图：" prop="goods_images">
            <UploadImageListInfo ref="uploadImageListRef" group="goods_images" v-model:disabledbtn="disabledbtn" v-model:loading="loading" v-model:imageList="goodsImageList" :imageNum="imageNum" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left"><span class="title-left-color">规格信息</span></el-divider>
      <!-- 规格信息 -->
      <SpecInfo :toggleState="toggleState" :specList="specList" v-model:form="form" v-model:disabledbtn="disabledbtn" v-model:loading="loading" ref="specRef" />
      <el-divider content-position="left"><span class="title-left-color">商品详情</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="广告详情：">
            <div>
              <div id="editor"></div>
              <div>描述：通用活动页面的详情的展示</div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import UploadImageInfo from "@/components/common/UploadImageInfo.vue";
import UploadImageListInfo from "@/components/common/UploadImageListInfo.vue";
import SpecInfo from "@/components/redPacketMallManage/mallGoodsInfo/SpecInfo.vue";
import UploaVideoInfo from "@/components/common/UploaVideoInfo.vue";
import { userEditor } from "@/hooks/userEditor";
import type { postOrPutType } from "@/constants";
import type { HasId, ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IMallGoodsDetail } from "@/types/redPacketMallManage/mallGoods";
import type { IMallCategory } from "@/types/mallCategory";
import type { IDictData } from "@/types/dict";
import type { IMallDeliver } from "@/types/redPacketMallManage/mallDeliver";
import { commonMallGoodsInfo, getMallGoodsByIdInfo } from "@/utils/api/mallGoods";
import type { ISpecItem } from "@/types/redPacketMallManage/spec";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  id: number;
  selectCategories: Array<IMallCategory>;
  selectFreighTemplate: Array<IMallDeliver>;
  selectStatus: Array<IDictData>;
  selectWhether: Array<IDictData>;
  selectPlatform: Array<IDictData>;
}
const { id, selectCategories, selectFreighTemplate, selectStatus, selectWhether, selectPlatform } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });
const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
  getMallCategoryInfo: [];
  getMallDeliverInfo: [];
}>();

const editor = ref();
const specRef = ref<InstanceType<typeof SpecInfo>>();

const isDisabledbtn = ref(false);
const goodsImageList = ref<Array<string>>([]);
const imageNum = ref<number>(0);
const formRef = useTemplateRef("formRef");
const uploadImageListRef = useTemplateRef("uploadImageListRef");
const methodType = ref<postOrPutType>("PUT");
const form = reactive<IMallGoodsDetail>({
  selling_poiont: "",
  goods_images: "",
  goods_content: "",
  goods_video: "",
  deliver_id: "",
  category_ids: [],
  platform_type: ["weChatPlatform", "alipayPlatform", "appPlatform"],
  spec_list: [],
  sku_list: [],
  is_goods_no: "",
  goods_image: "",
  goods_name: "",
  goods_no: "",
  id: 0,
  sales_initial: 0,
  sort: 0,
  status: "",
  statusName: "",
  update_specs: [],
  stock_total: 0,
  cost_price: "",
  official_price: "",
  red_packet_price: "",
  retail_price: "",
  wholesale_price: ""
});

const specList = ref<Array<ISpecItem>>([]);

let { handleInitEditor } = userEditor("#editor", handleChangeNewHtml);

const rules = reactive({
  category_ids: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
  goods_name: [{ required: true, message: "请填写商品名称", trigger: "blur" }],
  status: [{ required: true, message: "请选择商品状态", trigger: "blur" }],
  deliver_id: [{ required: true, message: "请选择运费模板", trigger: "blur" }],
  cost_price: [{ required: true, message: "请填写成本价", trigger: "blur" }],
  wholesale_price: [{ required: true, message: "请填写批发价", trigger: "blur" }],
  retail_price: [{ required: true, message: "请填写零售价", trigger: "blur" }],
  official_price: [{ required: true, message: "请填写淘宝价", trigger: "blur" }],
  red_packet_price: [{ required: true, message: "请填写最多可抵扣红包个数", trigger: "blur" }],
  goods_image: [{ required: true, message: "请上传商品主图", trigger: "blur" }],
  stock_total: [{ required: true, message: "请填写库存", trigger: "blur" }],
  sales_initial: [{ required: true, message: "请填写已售基数", trigger: "blur" }],
  goods_no: [{ required: true, message: "请填写货号", trigger: "blur" }],
  platform_type: [{ required: true, message: "请填写发布平台", trigger: "blur" }],
  sort: [{ required: true, message: "请填写排序", trigger: "blur" }]
});

onMounted(() => {
  editor.value = handleInitEditor();
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/*  */
watch(
  () => id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
    } else {
      form.id = newValue;
      handleGetAppUserByIdInfo(id);
    }
  }
);

/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;

  form.id = 0;
  imageNum.value = 0;
  goodsImageList.value = [];
  uploadImageListRef.value?.handleClearImage();
  specList.value = [];
  form.sku_list = [];
  editor.value?.txt.clear();
  formRef.value?.resetFields();
  formRef.value?.clearValidate();

  form.platform_type = ["weChatPlatform", "alipayPlatform", "appPlatform"];
}
/* 改变富文本内容 */
function handleChangeNewHtml(newHtml: string) {
  form.goods_content = newHtml;
}
/* 通过id获取前端账户详情信息 */
function handleGetAppUserByIdInfo(id: number) {
  toggleState(true);
  getMallGoodsByIdInfo<IMallGoodsDetail, HasId>({ id })
    .then(res => {
      form.category_ids = res.result.category_ids;
      form.selling_poiont = res.result.selling_poiont;

      form.goods_content = res.result.goods_content;
      form.goods_video = res.result.goods_video;
      form.deliver_id = res.result.deliver_id;
      form.cost_price = res.result.cost_price;
      form.goods_image = res.result.goods_image;
      form.goods_name = res.result.goods_name;
      form.goods_no = res.result.goods_no;
      form.id = res.result.id;
      form.official_price = res.result.official_price;
      form.red_packet_price = res.result.red_packet_price;
      form.retail_price = res.result.retail_price;
      form.sales_initial = res.result.sales_initial;
      form.sort = res.result.sort;
      form.status = res.result.status;
      form.stock_total = res.result.stock_total;
      form.wholesale_price = res.result.wholesale_price;
      form.is_goods_no = res.result.is_goods_no;
      form.platform_type = res.result.platform_type;

      form.goods_images = res.result.goods_images;
      if (res.result.goods_images !== "") {
        goodsImageList.value = res.result.goods_images.split(",");
        imageNum.value = goodsImageList.value.length;
      }

      editor.value.txt.append(res.result.goods_content);

      form.sku_list = res.result.sku_list;
      res.result.spec_list.forEach(item => {
        item.inputVisible = false;
        item.inputValue = "";
        return item;
      });
      specList.value = res.result.spec_list;
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 校验数据 */
function handleVerifyData() {
  /* 有规格名称，必须要有规格值 */
  for (let i = 0; i < specRef.value!.spec_list!.length; i++) {
    const element = specRef.value!.spec_list[i];
    if (element.spec_value.length === 0) {
      ElMessage.warning(`请填写${element.name}规格值`);
      return false;
    }
  }

  if (isNaN(Number(form.cost_price))) {
    ElMessage.warning(`请正确填写成本价的格式`);
    return false;
  }
  if (isNaN(Number(form.wholesale_price))) {
    ElMessage.warning(`请正确填写批发价的格式`);
    return false;
  }
  if (isNaN(Number(form.retail_price))) {
    ElMessage.warning(`请正确填写零售价的格式`);
    return false;
  }
  if (isNaN(Number(form.official_price))) {
    ElMessage.warning(`请正确填写淘宝价的格式`);
    return false;
  }
  if (isNaN(Number(form.red_packet_price))) {
    ElMessage.warning(`请正确填写最多可抵扣红包的格式`);
    return false;
  }

  if (Number(form.cost_price) <= 0) {
    ElMessage.warning(`成本价需大于0`);
    return false;
  }
  if (Number(form.wholesale_price) <= 0) {
    ElMessage.warning(`批发价需大于0`);
    return false;
  }
  if (Number(form.retail_price) <= 0) {
    ElMessage.warning(`零售价需大于0`);
    return false;
  }
  if (Number(form.official_price) <= 0) {
    ElMessage.warning(`淘宝价需大于0`);
    return false;
  }
  if (Number(form.red_packet_price) < 0) {
    ElMessage.warning(`最多可抵扣红包需大于等于0`);
    return false;
  }

  if (Number(form.cost_price) > Number(form.wholesale_price)) {
    ElMessage.warning(`成本价必须小于批发价`);
    return false;
  }
  if (Number(form.cost_price) > Number(form.retail_price)) {
    ElMessage.warning(`成本价必须小于零售价`);
    return false;
  }
  if (Number(form.wholesale_price) > Number(form.retail_price)) {
    ElMessage.warning(`批发价必须小于零售价`);
    return false;
  }
  if (Number(form.red_packet_price) > Number(form.retail_price)) {
    ElMessage.warning(`最多可抵扣红包必须小于等于零售价`);
    return false;
  }

  return true;
}

/* 新增修改之前修改数据 */
function handleChangeData() {
  if (form.stock_total === 0) {
    form.status = "outOfStock";
  }
  /* 格式化轮播图片 */
  if (form.goods_images == "") {
    form.status = "hasBeenRemoved";
  }
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    if (!handleVerifyData()) return;
    handleChangeData();
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonMallGoodsInfo(form, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}
function getMallCategoryInfo() {
  emit("getMallCategoryInfo");
}

function getMallDeliverInfo() {
  emit("getMallDeliverInfo");
}
</script>

<style lang="scss" scoped>
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
/* 富文本编辑 start */
#editor {
  width: 397px;
  :deep(.w-e-toolbar) {
    z-index: 1001 !important;
  }
  :deep(.w-e-text-container) {
    z-index: 1000 !important;
  }
}
/* end */
</style>
